import router from './index';

const modules = import.meta.glob('@/views/**/*.vue');

const formatChildren = (item) => {
  const result = [];
  item.children.forEach((m) => {
    if (m?.children?.length) {
      result.push(formatChildren(m));
    } else if (!m?.path.includes('http', 'https')) {
      result.push(m);
    }
  });
  return result;
};

export default function (menus) {
  if (!menus || !menus.value.length) return;
  menus.value.forEach((item) => {
    if (!item.path?.includes('http', 'https') && !item?.children?.length) {
      router.addRoute('root', {
        path: item.path,
        name: item.name,
        component: modules[`/src/views${item.path}.vue`],
      });
    }
    if (item?.children?.length) {
      const children = formatChildren(item);
      children.forEach((child) => {
        router.addRoute('root', {
          path: child.path,
          name: child.name,
          component: modules[`/src/views${child.path}.vue`],
        });
      });
    }
  });
}
